#pragma once
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"
#include "Session.hpp"
namespace HttpServerModule
{
    using http_hander_t = std::function<void(Request& req,Response& res)>;
    using namespace TcpserverModule;
    class HttpServer
    {
    public:
        HttpServer(int port)
            : _tsvr(std::make_shared<TcpServer>(port))
            ,_manager(std::make_shared<SessionManager>())
        {
            _tsvr->RegisterHandler([this](SockPtr ret, InetAddr client)
                                   { return this->Handler(ret, client); });
        }
        void Start()
        {
            _tsvr->Loop();
        }
        void RegisterHander(std::string path,http_hander_t server)
        {
            _route[path] = server;
        }
        bool CheckSafe(std::string& path)
        {
            auto it = _route.find(path);
            return it != _route.end();
        }
        void Handler(SockPtr ret, InetAddr client)
        {
            LOG(LogLevel::INFO) << "new client fd: " << ret->FD() << "client info: " << client.Addr();
            // 接受数据
            std::string http_str;
            ret->TcpRecv(&http_str);

            std::cout << "--------------------------------" << std::endl;
            std::cout << http_str << std::endl;
            std::cout << "--------------------------------" << std::endl;
            
            Request req;
            Response res;

            //1. 静态请求 
            req.Deserialize(http_str);
            
            if (req.HasArgs())
            {
                static int number = 0;
                std::string username = "user" + std::to_string(number++);
                session_ptr s = std::make_shared<Session>(username,"Logined");
                std::string sessionid = _manager->AddSession(s);
                res.AddHeader("Set-Cookie: " + sessionid);
            }
            else 
            {
                std::string sessionid = req.GetSessionId();
                if (sessionid.empty())
                {

                }
                else 
                {

                }
            }


            res.SetCode(200);
            std::string body  = "<html><body><p>Hello,World!</p></body></html>"; //硬编码，无论访问什么路径都返回hello world
            res.SetBody(body);

            //认为到现在过来的是一个完整的报文，不进行读取不完善处理
            std::string returnstr;
            res.Serialize(&returnstr);
            ret->TcpSend(returnstr);
        }
       
        ~HttpServer() {}

    private:
        std::shared_ptr<TcpServer> _tsvr;
        std::unordered_map<std::string,http_hander_t> _route;
        std::shared_ptr<SessionManager> _manager;
    };
}